<style scoped>

</style>
<template>
    <div id='myApp'>
        <Row style="margin-bottom: 10px;border-bottom: 1px solid #eeeeee;">
            <Col span="4" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-add-circle" />&nbsp;&nbsp;
                <span style="color: black;">系统管理&nbsp;&nbsp;>&nbsp;&nbsp;</span>
                用户
            </span>
            </Col>
            <Col span="5" offset="15">
            <Button @click="openModaluser" type="success" label="small"
                style="border: none;height: 27px; float: right;">创建用户</Button>
            </Col>
            <Modal v-model="modal1" width="410">
                <p slot="header" style="color: #2d8cf0;">
                    <Icon type="ios-information-circle"></Icon>
                    <span>{{currentId==false?'创建用户':'修改用户'}}</span>
                </p>
                <div>
                    <Form ref="ruleForm" :rules="ruleValidate" :model="ruleForm" :label-width="100">
                        <FormItem prop="realName" label="姓名：">
                            <Input v-model="ruleForm.realName" />
                        </FormItem>
                        <FormItem prop="account" label="账号：">
                            <Input v-model="ruleForm.account" :disabled="currentId"  />
                        </FormItem>
                        <FormItem prop="role" label="角色：">
                            <Select v-model="ruleForm.role" placeholder=''>
                                <Option value="管理员">管理员</Option>
                                <Option value="操作员">操作员</Option>
                            </Select>
                        </FormItem>
                        <template v-if="currentId==false">
                            <FormItem prop="password" label="密码：">
                                <Input type="password" v-model="ruleForm.password" />
                            </FormItem> 
                            <FormItem prop="passwdCheck" label="确认密码：">
                                <Input type="password" v-model="ruleForm.passwdCheck" />
                            </FormItem>
                        </template>
                        <FormItem prop="enabled" label="状态：">
                            <Checkbox v-model="ruleForm.enabled" >启用</Checkbox>
                        </FormItem>
                    </Form>
                </div>
                <div slot="footer">
                    <template v-if="currentId==false">
                        <Button type="primary" @click="addUser('ruleForm')">确定</Button>
                    </template>
                    <template v-else>
                        <Button type="primary" @click="edituser(1)">保存</Button>
                    </template>                  
                </div>
            </Modal>
            <Modal v-model="modal2" width="410">
                <p slot="header" style="color: #2d8cf0;">
                    <Icon type="ios-information-circle"></Icon>
                    <span>修改密码</span>
                </p>
                <div>
                    <Form ref="ruleFormEdit" :rules="ruleValidateEdit" :model="ruleFormEdit" :label-width="100">                        
                        <FormItem prop="oldPassword" label="原始密码：">
                            <Input type="password" disabled v-model="oldPassword" />
                        </FormItem> 
                        <FormItem prop="password" label="新密码：">
                            <Input type="password" v-model="ruleFormEdit.password" />
                        </FormItem> 
                        <FormItem prop="passwdCheck" label="确认密码：">
                            <Input type="password" v-model="ruleFormEdit.passwdCheck" />
                        </FormItem>                        
                    </Form>
                </div>
                <div slot="footer">
                  <Button type="primary" @click="savePassword">保存</Button>
                </div>
            </Modal>
        </Row>
        <Table :columns="httpColumns" :data="httpData"></Table>
        <div style="float: right; margin-top: 15px">
            <Page :total="dataCount" :page-size="pageSize" show-total class="paging" @on-change="changepage"
                @on-page-size-change="pages" show-elevator show-total></Page>
        </div>
    </div>
    </div>
</template>
<script>

    import { mapState, mapActions } from 'vuex'
    import zmitiUtil from '../../lib/util'
    export default {
        computed: mapState({
            Authorization: state => state.Authorization
        }),

        data() {
            const validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.passwdCheck !== '') {
                        // 对第二个密码框单独验证
                        this.$refs.ruleForm.validateField('passwdCheck');
                    }
                    callback();
                }
            };
            const validatePassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再一次输入密码'));
                } else if (value !== this.ruleForm.password) {
                    callback(new Error('两次密码不一致!'));
                } else {
                    callback();
                }
            };
            /*修改密码*/
            const validateEditPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleFormEdit.passwdCheck !== '') {
                        // 对第二个密码框单独验证
                        this.$refs.ruleFormEdit.validateField('passwdCheck');
                    }
                    callback();
                }
            };
            const validateEditPassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再一次输入密码'));
                } else if (value !== this.ruleFormEdit.password) {
                    callback(new Error('两次密码不一致!'));
                } else {
                    callback();
                }
            };

            return {
                passwordConfirm:'',
                currentId:false,
                ruleForm: {
                    realName: '',
                    account: '',
                    role: '',
                    password:'',
                    passwdCheck:'',
                    enabled:true
                },
                ruleFormEdit: {
                    oldPassword:'',
                    password:'',
                    passwdCheck:''
                },
                ruleValidate: {
                    realName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    account: [
                        { required: true, message: '请输入帐号', trigger: 'blur' }
                    ],
                    password: [
                        {required: true, validator: validatePass, trigger: 'blur' }
                    ],
                    passwdCheck: [
                        {required: true, validator: validatePassCheck, trigger: 'blur' }
                    ],
                },
                ruleValidateEdit: {
                    password: [
                        {required: true, validator: validateEditPass, trigger: 'blur' }
                    ],
                    passwdCheck: [
                        {required: true, validator: validateEditPassCheck, trigger: 'blur' }
                    ],
                },
                modal1: false,
                modal2:false,
                dataCount: 0,
                pageSize: 10,
                ajaxHttpData: [],
                xia: 0,
                httpColumns: [
                    {
                        title: '编号',
                        width:80,
                        key: 'num',
                        align: 'center',
                        render:(h,params)=>{
                            let nums = params.index+1;
                            return h('div',{},nums)
                        }
                    },
                    {
                        title: '用户姓名',
                        width:100,
                        key: 'realName',
                        align: 'center'
                    },
                    {
                        title: '账号',
                        key: 'account',
                        align: 'center'
                    },
                    {
                        title: '角色',
                        width:100,
                        key: 'role',
                        align: 'center'
                    },
                    {
                        title: '是否限制',
                        width:100,
                        key: 'enabled',
                        align: 'center',
                        render:(h,params)=>{
                            return h('div',{},params.row.enabled==true?'是':'否')
                        }
                    },
                    {
                        title: '操作',
                        // key: 'operate',
                        width: 220,
                        align: 'center',
                        render: (h, params) => {
                            const row = params.row;
                            return h('div', [
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type: 'text'
                                    },
                                    style: {
                                        marginRight: '5px',
                                        color:'#2d8cf0'
                                    },
                                    on: {
                                        click: () => {
                                            // 查看用户
                                            this.viewUser(params.row.account,1);
                                        }
                                    }
                                }, '查看'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type: 'text'
                                    },
                                    style: {
                                        marginRight: '5px',
                                        color:'#2d8cf0'
                                    },
                                    on: {
                                        click: () => {
                                            // 修改密码
                                            this.openModalPassword(params.row.account,params.row.password)                                           
                                        }
                                    }
                                }, '修改密码'),
                                h('Poptip', {
                                      props: {
                                          confirm: true,
                                          type: 'error',
                                          size: 'large',
                                          title: '你确定要删除吗?',
                                          transfer:true
                                      },

                                      on: {
                                          'on-ok': () => {
                                             this.deleteUser(params.row.account); 
                                          }
                                      }
                                  }, [
                                      h('Button', {
                                        props: {
                                            size: 'small',
                                            type: 'text'
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            marginRight: '5px',
                                            color:'#ed4014'
                                        }
                                      },'删除')
                                  ])
                            ]);
                        }
                    }

                ],
                httpData: [],
                oldPassword:'',//旧密码
            }
        },
        mounted() {
            // 获取用户列表，待修改
            let _this = this;
            _this.getDataList()
        },
        watch:{
            modal1(newValue,oldValue){
                if(!newValue){
                    this.ruleForm= {
                        realName: '',
                        account: '',
                        role: '',
                        password:'',
                        passwdCheck:'',
                        enabled:true
                    }
                    this.$refs['ruleForm'].resetFields();
                }
            }
        },
        methods: {
            getDataList(){//列出所有用户
                var _this = this;                
                var path='user/list';
                zmitiUtil.Ajax(path).then(res => {
                    var data = res.data;               
                    
                    if(res.data.length>0){
                        _this.httpData = res.data;
                        _this.dataCount=_this.httpData.length
                    }else{
                        _this.httpData=[];
                        _this.dataCount=0;
                    }
                    
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            openModaluser(){//打开添加用户
                var _this = this;
                _this.modal1=true;
                _this.currentId=false;//添加用户
                _this.ruleForm= {
                    realName: '',
                    account: '',
                    role: '',
                    password:'',
                    passwdCheck:'',
                    enabled:true
                }
            },
            openModalPassword(account,password){//打开修改密码
                var _this = this;
                _this.modal2=true;
                _this.oldPassword=password;
                _this.viewUser(account,2);
                //console.log(_this.httpData[index],'_this.httpData[index]');
            },
            addUser(name) {
                var _this = this;             
                var path='user/create';
                var postData = _this.ruleForm;
                console.log(postData,'postData');
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        zmitiUtil.Ajax(path,postData).then(res => {
                            var data = res.data;
                            console.log(data,'data')
                            if(res.data.code==1){
                                _this.modal1=false;
                                _this.$Message.success('添加成功！');
                                _this.$refs[name].resetFields();
                                _this.getDataList();
                            }else{
                                _this.$Message.error(res.data.result);
                            }
                        }).catch((error) => {
                            console.log(error,'error');
                        });
                    } else {
                        this.$Message.error('请填写完整!');
                    }
                })
            },
            viewUser(account,type){//查看用户
                var _this = this;
                if(type==1){
                    _this.modal1=true;
                    _this.currentId=true;
                }else{
                    /*重置修改密码*/
                    _this.ruleFormEdit.password='';
                    _this.ruleFormEdit.passwdCheck='';
                }    

                var path='user/view';
                var postData = {
                    account
                };
                console.log(postData,'查看用户postData')
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    console.log(data,'查看用户');
                    _this.ruleForm={
                        account:res.data.account,
                        enabled:res.data.enabled,
                        password:res.data.password,
                        realName:res.data.realName,
                        role:res.data.role
                    }
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            edituser(type){//修改用户
                /*type=1修改用户，type=2修改密码*/
                var _this = this;             
                var path='user/update';
                var postData = _this.ruleForm;
                console.log(postData,'postData');

                if(type==2){
                    /*修改密码*/
                    this.$refs['ruleFormEdit'].validate((valid) => {
                        if (valid) {
                            zmitiUtil.Ajax(path,postData).then(res => {
                                var data = res.data;
                                console.log(data,'data')
                                if(res.data.code==1){
                                    _this.modal2=false;//关闭修改密码
                                    _this.$Message.success('密码修改成功！');                                    
                                    _this.getDataList();
                                }else{
                                    _this.$Message.error(res.data.result);
                                }
                            }).catch((error) => {
                                console.log(error,'error');
                            });
                        }else{
                            this.$Message.error('请填写完整!');
                        }
                    })
                }else{
                    zmitiUtil.Ajax(path,postData).then(res => {
                        var data = res.data;
                        console.log(data,'data')
                        if(res.data.code==1){
                            _this.modal1=false;//关闭修改窗口
                            _this.$Message.success('修改成功！');                            
                            _this.getDataList();
                        }else{
                            _this.$Message.error(res.data.result);
                        }
                    }).catch((error) => {
                        console.log(error,'error');
                    });
                }
            },
            deleteUser(account){//删除用户
                var _this = this;             
                var path='user/delete';
                var postData = {
                    account
                };
                console.log(postData,'删除用户postData')
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    console.log(data,'data')
                    if(res.data.code==1){
                        _this.$Message.success('删除成功！');
                        _this.getDataList();
                    }else{
                        _this.$Message.error(res.data.result);
                    }
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            savePassword(){//修改密码
                var _this = this;
                _this.ruleForm.password = _this.ruleFormEdit.password;

                console.log(_this.ruleForm,'修改密码');
                setTimeout(()=>{
                    _this.edituser(2);
                },300)
            },
            pages(num) { //修改每页显示条数时调用
                this.pageSize = num;
                this.changepage(1);
            },
            // // 获取用户列表，待修改
            changepage(index) {
                //index当前页码
                console.log('index = ' + index)
                this.xia = (index - 1) * this.pageSize;

                let _this = this;
                console.log('_this.xia = ' + _this.xia)

                
            }
        },
        created() {
            // this.handleListApproveHttp();
        }
    }
</script>